package com.hfzy.ihk.common.support.againtask;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * 延时队列中的消息体将任务封装为消息体
 * @param <T>
 */
public class DelayTask <T extends Runnable> implements Delayed {
    private final long time;
    private final DelayWorker task; // 任务类，

    /**
     *
     *            超时时间(秒)
     * @param task
     *            任务
     */
    public DelayTask(DelayWorker task) {
       // this.time = System.nanoTime() + task.getTimeout();
        this.time = System.nanoTime() + task.getTimeout(); //到期时间=当前时间加延迟时间
        this.task = task;
    }

    @Override
    public int compareTo(Delayed o) {
        // TODO Auto-generated method stub
        DelayTask other = (DelayTask) o;
        long diff = time - other.time;
        if (diff > 0) {
            return 1;
        } else if (diff < 0) {
            return -1;
        } else {
            return 0;
        }
    }

    @Override
    public long getDelay(TimeUnit unit) {
        // TODO Auto-generated method stub
      //  return unit.convert(this.time - System.currentTimeMillis(), TimeUnit.MICROSECONDS);
        return unit.convert(this.time - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int hashCode() {
        return task.hashCode();
    }

    public DelayWorker getTask() {
        return task;
    }


}
